package com.lmaos.basetools.dbconn;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

import com.lmaos.basetools.base.SParamMap;
import com.lmaos.basetools.sText.TextUtils;

public class SqlExecute {
	
	private Connection conn;
	private String sql;
	private Object[] params;
	private String sqlEnds;
	private BaseDao baseDao;
	
	public SqlExecute(Connection conn, String sql, Object[] params, BaseDao baseDao) {
		super();
		this.conn = conn;
		this.sql = sql;
		this.params = params;
		this.baseDao = baseDao;
	}
	public SqlExecute setSqlEnds(String sqlEnds) {
		this.sqlEnds = sqlEnds;
		return this;
	}
	/**
	 * 说明：设置排他锁		<br>
	 * 时间：2017年7月11日 上午11:08:59
	 *
	 * @return
	 */
	public SqlExecute setExclusiveLock(){
		return setSqlEnds("FOR UPDATE");
	}
	/**
	 * 说明：共享锁		<br>
	 * 时间：2017年7月11日 上午11:10:34
	 *
	 * @return
	 */
	public SqlExecute setSharedLock(){
		return setSqlEnds("LOCK IN SHARE MODE");
	}
	public SqlExecute setSql(String sql) {
		this.sql = sql;
		return this;
	}
	public String getSrcSql(){
		return sql;
	}
	public String getSql(){
		String exeSql = sql;
		if(!TextUtils.isBlank(sqlEnds)){
			exeSql +=(" "+ sqlEnds);
		}
		return exeSql;
	}
	public List<SParamMap> select(){
		String exeSql = getSql();
		return DBConn.select(exeSql, conn, params);
	}
	public <T>List<T> selectObjs(Class<T> type,Map<String, String> nameMapping){
		List<SParamMap> datas = select();
		List<T> objs = baseDao.toTBObjects(datas, type, nameMapping);
		return objs;
	}
	public <T>T selectOne(Class<T> type,Map<String, String> nameMapping){
		List<T> objs = selectObjs(type, nameMapping);
		if(objs.size()>0){
			return objs.get(0);
		}
		return null;
	}
}
